<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="分组管理" name="group">
      <el-row class="admin">
        <el-row class="marBottom20">
          <el-button type="primary" @click="groupEdit('添加分组')">添加分组</el-button>
        </el-row>
        <el-row>
          <el-table
            :data="groupData"
            style="width: 100%">
            <el-table-column
              label="#"
              width="100">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="组名"
              width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.groupName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="人数"
              width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.peopleNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="memberView(scope.row._id)">
                  成员查看
                </el-button>
                <el-button
                  size="mini"
                  @click="groupEdit('组编辑',scope.row._id, scope.row)">
                  组编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="groupDelete(scope.row._id, scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="成员管理" v-if="activeName === 'member'" name="member">
      <el-row class="admin">
        <el-row class="marBottom20">
          <el-button type="primary" @click="dialogVisible = true;memberOperate = true">添加成员</el-button>
        </el-row>
        <el-row>
          <el-table
            :data="memberData"
            style="width: 100%">
            <el-table-column
              label="用户名"
              width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.userName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="密码"
              width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.password }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="昵称"
              width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.nikeName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="dialogVisible = true;memberOperate = false;memberEditData = scope.row">编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="memberDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-dialog
          title="成员编辑"
          :visible.sync="dialogVisible"
          width="30%">
          <el-form ref="form" :rules="memberEditRules" :model="memberEditData" label-width="80px">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="memberEditData.userName"></el-input>
            </el-form-item>
            <el-form-item label="密　码" prop="password">
              <el-input v-model="memberEditData.password"></el-input>
            </el-form-item>
            <el-form-item label="昵　称" prop="nikeName">
              <el-input v-model="memberEditData.nikeName"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="menberModelClose">取 消</el-button>
            <el-button type="primary" @click="menberModelSubmit">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
    </el-tab-pane>
    <el-tab-pane :label="editName" v-if="activeName === 'groupEdit'" name="groupEdit">
      <div class="group-edit">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="分组名称">
            <el-input v-model="form.groupName" style="width: 300px"></el-input>
          </el-form-item>
          <div>
            <el-tree
              :data="menuData"
              show-checkbox
              node-key="id"
              ref="tree"
              :props="defaultProps">
               <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span style="margin-left: 20px">
                   <span v-if="data.meta.isAuth" style="font-size:12px;color:#999">该菜单下有按钮需要设置</span>
                   <el-checkbox :label="authBtnData[data.meta.auth].name" v-model="authCheckedName"
                                v-if="data.meta.auth"></el-checkbox>
                </span>
              </span>
            </el-tree>
          </div>
          <el-form-item style="margin-top: 20px">
            <el-button type="primary" size="small" @click="onSubmit">立即创建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
  export default {
    data() {
      return {
        dialogVisible: false, // 弹框显示条件
        memberOperate: true, // true 为成员添加  false 为成员编辑
        editName: '', // 组编辑、组添加
        activeName: 'group', // member
        groupData: [],
        form: {  // 新增或者编辑 组信息
          id: '',
          groupName: '',
          menuData: [],
          range: {},
          CheckedKey: []
        },
        menuData: [], // 菜单数据
        defaultProps: {  // 树形图配置参数
          children: 'children',
          label: 'name'
        },
        authBtnData: [], // 所有权限按钮列表
        authCheckedName: [],  // 选中的权限按钮
        memberData: [], // 分组成员列表
        memberEditData: { // 成员表单
          userName: '',
          password: '',
          nikeName: ''
        },
        memberEditRules: { // 成员信息编辑验证
          userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
          password: [{required: true, message: '请输入密码', trigger: 'blur'}],
          nikeName: [{required: true, message: '请输入昵称', trigger: 'blur'}]
        },
        groupId: ''// 用于添加或者编辑成员信息时重新获取成员信息
      }
    },
    created() {
      this.menuData = JSON.parse(this.$store.state.user.menu.menuData)
      this.authBtnData = this.$store.state.user.menu.range
    },
    mounted() {
      this.getGroup()
    },
    methods: {
      getGroup() {
        this.$ajax.post('/index/getGroupList')
          .then((res) => {
            if (res.data.code === -1) {
              this.$message.error(res.data.msg)
            }
            this.groupData = res.data.data
          })
      },
      // 树形图获取 全部选中的节点 （element-ui未提供改方法）
      getCheckedNodesAll(treeData, elm) {
        let isChecked = (data) => {
          let temporaryArr = []
          let temporaryData = []
          if (data.indeterminate) {
            temporaryData = Object.assign({}, data.data)
            temporaryData.children = []
            temporaryArr.push(temporaryData)
            for (let i = 0; data.childNodes.length > i; i++) {
              if (data.childNodes[i].indeterminate) {
                temporaryArr[0].children.push(isChecked(elm.getNode(data.childNodes[i])))
              } else if (data.childNodes[i].checked) {
                temporaryArr[0].children.push(data.childNodes[i].data)
              }
            }
          } else if (data.checked) {
            temporaryArr.push(data.data)
          }
          return temporaryArr
        }
        let menu = []
        for (let o = 0; treeData.length > o; o++) {
          let CheckedArr = isChecked(elm.getNode(treeData[o].id))
          if (CheckedArr.length > 0) menu.push(CheckedArr[0])
        }
        return menu
      },
      // 组编辑提交
      onSubmit() {
        this.form.menuData = JSON.stringify(this.getCheckedNodesAll(this.menuData, this.$refs.tree))
        this.form.CheckedKey = this.$refs.tree.getCheckedKeys()
        let judge = (condition, msg) => {
          if (condition <= 0) {
            this.$message({
              type: 'info',
              message: msg
            })
            return true
          }
          return false
        }
        if (judge(this.form.groupName.length, '分组名称不能为空！') || judge(this.form.menuData.length, '菜单不能为空！')) {
          return
        }
        for (let i in this.authBtnData) {
          if (this.authCheckedName.indexOf(this.authBtnData[i].name) === -1) {
            this.authBtnData[i].auth = false
          } else {
            this.authBtnData[i].auth = true
          }
        }
        this.form.range = this.authBtnData
        this.$ajax.post('/index/addGroup',
          {
            data: this.form
          }).then((res) => {
          if (res.data.code === -1) {
            this.$message.error(res.data.msg);
          } else if (res.data.code === 0) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.getGroup()
            this.activeName = 'first'
          }
        })
      },
      groupEdit(editName, id, row) {
        this.activeName = 'groupEdit'
        this.editName = editName
        if (editName === '组编辑') {
          this.$ajax.post('/index/getGroupInfo', {id: id})
            .then((res) => {
              if (res.data.code === -1) {
                this.$message.error(res.data.msg)
              }
              this.$nextTick(() => {
                this.form.groupName = res.data.data[0].groupName
                this.form.id = id
                for (let n in res.data.data[0].range) {
                  if (res.data.data[0].range[n].auth) {
                    this.authCheckedName.push(res.data.data[0].range[n].name)
                  }
                }
                this.$refs.tree.setCheckedKeys(res.data.data[0].CheckedKey)
              })
            })
        }
      },
      groupDelete(id, row) {
        console.log(id, row);
        this.$confirm('此操作将永久删除该组(同时会删除组中的成员), 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.post('/index/groupDelete', {id: id})
            .then((res) => {
              if (res.data.code === 0) {
                this.getGroup()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              } else {
                this.$message.error(res.data.msg);
              }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 编辑成员信息取消
      menberModelClose() {
        this.dialogVisible = false
        this.memberEditData = {
          userName: '',
          password: '',
          nikeName: ''
        }
      },
      // 编辑成员信息提交
      menberModelSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let url = ''
            let data = {}
            if (this.memberOperate) {
              url = '/index/addUser'
              data = {...this.memberEditData, groupId: this.groupId}
            } else {
              url = '/index/editUser'
              data = this.memberEditData
            }
            this.$ajax.post(url, data).then((data) => {
              if (data.data.code === 1) {
                this.dialogVisible = false
                this.getMemberList(this.groupId)
                this.memberEditData = {
                  userName: '',
                  password: '',
                  nikeName: ''
                }
              } else {
                this.$message({
                  type: 'info',
                  message: data.data.msg
                });
              }
            })
          } else {
            return false;
          }
        })
      },
      getMemberList(id) {
        this.$ajax.post('/index/getMemberList', {id: id})
          .then((res) => {
            if (res.data.code === -1) {
              this.$message.error(res.data.msg)
            }
            this.memberData = res.data.data
          })
      },
      // 成员页面
      memberView(id) {
        this.activeName = 'member'
        this.groupId = id
        this.getMemberList(id)
      },
      // 删除群成员
      memberDelete(id, row) {
        this.$confirm('此操作将永久删除该成员?, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.post('/index/memberDelete', {id: row._id, groupId: row.groupId[0]}).then(data => {
            if (data.data.code === 1) {
              this.getMemberList(this.groupId)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'info',
                message: data.data.msg
              });
            }
          })
        }).catch(() => {
        });
      },
    },
    watch: {
      activeName(news, old) {
        console.info(this.activeName)
        console.info(news, old)
        if (old === 'groupEdit') {
          this.form = {
            id: '',
            groupName: '',
            menuData: [],
            range: {},
            CheckedKey: []
          }
          this.authCheckedName = []
        }else if(news === 'group' && old === 'member'){
          this.getGroup()
        }
      }
    }
  }
</script>
<style scoped lang="less">
  @import "admin.less";

  .marBottom20 {
    margin-bottom: 20px;
  }

  .el-tabs {
    padding: 0 20px;
  }

  .model-row {
    margin-bottom: 10px;
    label {
      width: 50px;
      height: 34px;
      line-height: 34px;
      margin-left: -100%;
    }
    .input-div {
      width: 100%;
      float: left;
      .input-page {
        margin-left: 50px;
        input {
          width: 100%;
          height: 32px;
          border: 1px solid #e0e0e0;
          border-radius: 3px;
          text-indent: 10px;
        }
      }
    }
  }
</style>
